<template>
  <view>
    <view class="main-header">
      <text>{{ $t("环境分析") }}</text>
    </view>
    <view class="main-pingfen">
      <view class="identifylabelids-button">
        <view class="identifylabelids-button-item">
          <uv-button :custom-style="miniButton" :color="blue_selected === id ? '#748ee2' : '#aaaaaa'" text="概览"
            @click="blue_selected = id">
          </uv-button>
        </view>
        <view v-for="(v, i) in bluelist" :key="i" class="identifylabelids-button-item">
          <uv-button :custom-style="miniButton" :color="blue_selected === v.id ? '#748ee2' : '#aaaaaa'" :text="v?.name"
            @click="blue_selected = String(v.id)"></uv-button>
        </view>
      </view>
    </view>
    <view class="container">
      <slot :show="show && blueshow" id="mychart-dom-blue" canvasId="mychart-blue"
        :ec="{ onInit: (canvas: any, width: string | number, height: string | number, dpr: number) => setblue(canvas, width, height, dpr) }">
      </slot>
    </view>
  </view>
</template>

<script setup lang="ts">
import { getchildrenlast } from "@/util";
import { miniButton } from "@/util/style";
import { max, reverse } from "lodash-es";
import { shallowRef, watch } from "vue";
import { computed, ref } from "vue";
//@ts-ignore
const echarts = require("../../wxcomponents/ec-canvas/echarts");

import { nextTick } from "vue";

import { navigateTo } from "@/util/navigator";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
const $t = useI18n().t;
interface Ip {
  id: string;
  list: Eps.identifylabelEntity[];
  change(
    identifycommentlabels: string[],
    p?: number,
    d?: number
  ): {
    xAxisdata: string[];
    name: string[];
    series: {
      value: number;
      type: string;
      date: string;
      name: string;
      color: string;
    }[][];
    data: {
      value: number;
      type: string;
      date: string;
      name: string;
      color: string;
    }[];
    parent: {
      count: number;
      name: string;
      id1: string | undefined;
      id2: string | undefined;
      value: number;
    }[];
    parent2: {
      count: number;
      name: string;
      id1: string | undefined;
      id2: string | undefined;
      value: number;
    }[];
  };
  show: boolean;
  shopdata: any[];
  _feedbackTime: string[];
  feedbackTime: string[];
}
const p = defineProps<Ip>();

const chart = shallowRef();
const blue_selected = ref<string>(p.id);
const blueshow = ref(true);
const bluelist = computed(() => {
  const data = p.list
    .filter((c) => String(c.parentId) === p.id)
    .sort((a, b) => Number(a.orderNum) - Number(b.orderNum));
  return data;
});
const blue_identifycommentlabels = ref<string[]>([]);
watch(
  () => blue_selected.value,
  () => {
    nextTick(() => {
      chart.value.setOption(setoption(), { notMerge: true });
    });
  }
);

function setoption() {
  blue_identifycommentlabels.value = getchildrenlast(
    p.list.find((c) => String(c.id) === blue_selected.value)?.children
  ).map((e) => e.id);

  const color = [
    "#4964AF",
    "#4D85D8",
    "#A8DAFF",
    "#5f27cd",
    "#10ac84",
    "#feca57",
    "#f368e0",
    "#00d2d3",
    "#341f97",
    "#576574",
  ];
  if (blue_selected.value === p.id) {
    const { parent, series } = p.change(blue_identifycommentlabels.value, 1, 0);
    const option = {
      title: false,
      tooltip: {
        trigger: "item",
        formatter: "{b} : {c}",
      },
      polar: {
        radius: [30, "80%"],
      },
      angleAxis: {
        max: 1 || max(parent.map((e) => e.count)),
        startAngle: 90,
        show: false,
      },
      radiusAxis: {
        type: "category",
        show: false,
      },
      series: {
        type: "bar",
        data: reverse(
          parent.map((e, k) => {
            return {
              name: e.name,
              value: e.value,
              itemStyle: {
                color: color[k],
              },
            };
          })
        ),
        coordinateSystem: "polar",
        label: {
          show: true,
          position: "middle",
          formatter: "{b}: {c}",
        },
      },
      graphic: {
        elements: [
          {
            type: "text",
            z: 100,
            left: "center", // 相对位置
            top: "center", // 相对位置
            style: {
              fill: "#333", // 文本颜色
              text: parent
                .map((e) => e.value)
                .reduce(function (a, b) {
                  return a + b;
                }, 0), // 计算总和
              font: "18px sans-serif", // 文本样式
            },
          },
        ],
      },
    };
    return option;
  } else {
    const { series } = p.change(blue_identifycommentlabels.value, 2, 0);
    const option = {
      color: [
        "#FD754C",
        "#cccccc",
        "#ee5253",
        "#5f27cd",
        "#10ac84",
        "#feca57",
        "#f368e0",
        "#00d2d3",
        "#341f97",
        "#576574",
      ],
      title: false,
      tooltip: {
        trigger: "item",
        formatter: "{b} : {c}",
      },
      xAxis: {
        type: "category",
        data: series[0].map((e) => e.name),
        show: false,
      },
      legend: {
        top: "top",
        left: "left",
        data: ["当前周期", "上一周期"],
        selected: {
          "上一周期": false  // 将 "Lowest" 设置为默认不选中
        }
      },
      yAxis: {
        type: "value",
      },
      // dataZoom: [
      //     {
      //         preventDefaultMouseMove: false,
      //         moveOnMouseWheel: false,
      //         moveOnMouseMove: false,
      //         zoomOnMouseWheel: false,
      //         type: 'inside',
      //         start: 0,
      //         end: 100
      //     },
      //     {
      //         start: 0,
      //         end: 100,
      //         backgroundColor: '#fff',
      //         dataBackground: {
      //             lineStyle: {
      //                 color: '#FD754C',
      //             },
      //             areaStyle: {
      //                 color: '#FD754C',
      //             }
      //         },
      //         selectedDataBackground: {
      //             lineStyle: {
      //                 color: '#FD754C',
      //             },
      //             areaStyle: {
      //                 color: '#FD754C',
      //             }
      //         },
      //         fillerColor: '#FD754C30',
      //         showDetail: false,
      //         showDataShadow: false,
      //     }
      // ],
      series: [
        {
          name: "当前周期",
          data: series[0],
          type: "bar",
          sort: "descending",
          realtimeSort: true,
          label: {
            show: true,
            formatter: (value: any) => {
              if (value.value) {
                return value.name.split("").join("\n");
              }
              return "";
            },
            verticalAlign: "bottom",
            align: "left",
            position: "bottom",
            distance: -10,
            offset: [-5, 0],
          },
        },
        {
          name: "上一周期",
          data: series[1],
          type: "bar",
          label: {
            show: true,
            formatter: (value: any) => {
              if (value.value) {
                return value.name.split("").join("\n");
              }
              return "";
            },
            verticalAlign: "bottom",
            align: "left",
            position: "bottom",
            distance: -10,
            offset: [-5, 0],
            textBorderWidth: 0,
            textShadowBlur: 0,
          },
        },
      ],
    };
    return option;
  }
}

function click(e: any) {
  if (e.componentSubType == "bar") {
    if (blue_selected.value == p.id) {
      const n = p.list.find(
        (z) => String(z.parentId) === p.id && z.name === e.name
      );
      if (n) {
        blue_selected.value = String(n.id);
      }
    } else {
      const n = p.list.find((z) => z.name === e.name);
      const identifylabelid = [n?.id];
      const _shopdata = p.shopdata.filter((z) =>
        identifylabelid.includes(z.identifylabelid)
      );
      uni.setStorageSync("shopdata", JSON.stringify(_shopdata));
      navigateTo(
        `/pages/publicsentiment/shopdata?type=ai&starttime=${p._feedbackTime[0]
        }&endtime=${dayjs(p.feedbackTime[1]).format(
          "YYYY-MM-DD"
        )}&identifylabelid=${identifylabelid.join(",")}`
      );
    }
  }
}
function setblue(
  canvas: any,
  width: string | number,
  height: string | number,
  dpr: number
) {
  chart.value = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr, // new
  });

  chart.value.setOption(setoption(), { notMerge: true });
  canvas.setChart(chart.value);
  chart.value.on("click", click);
  return chart.value;
}
</script>
